<?php
namespace app\blogadmin\controller;

use think\Db;
use think\Request;
use app\blogadmin\model\Category as categoryM;

class Category extends Base{

    public function lst(){
        //获取栏目列表
        $cateM=new categoryM();
        $lst=$cateM->cateTree();
        $this->assign('cateLst',$lst);
        return $this->fetch();
    }


    public function add(){
        $categoryM = new categoryM();   //实例化模型
        if(Request::instance()->isPost()) {
            //获取提交的数据，实体化数据
            $data = input("post.");
            $info['cate_name'] = htmlspecialchars($data['cate_name']);
            $info['pid'] = $data['pid'];
            $info['type'] = $data['type'];

            $res =$categoryM->add($info);
            if ($res) {
                return json(['msg' => '添加数据成功', 'code' => '1']);
            } else {
                $this->error('');
                return json(['msg' => '添加数据失败', 'code' => '-1']);
            }
        }
        //获取所有的栏目
        $cateM=new categoryM();
        $cateLst=$cateM->cateTree();
        $this->assign('cateLst',$cateLst);

        return $this->fetch();
    }

    public function edit(){
       $id=Request::instance()->param('id');//获取用户id
       $cateM=new  categoryM();
       $cur_info=$cateM::get($id); //获取当前用户信息
        //获取管理员角色列表
       if(Request::instance()->isPost()){
            $data=Request::instance()->param();
            $info['cate_name'] = htmlspecialchars($data['cate_name']);
            $info['pid'] = $data['pid'];
            $info['type'] = $data['type'];
            $info['id']=$data['id'];

            $res=$cateM->upda($info);
            if($res){
                return json(['code'=>1,'msg'=>"修改数据成功"]);
            }else{
                return json(['code'=>-1,'msg'=>"修改数据失败"]);
            }
       }
        //获取所有的栏目
        $cateM=new categoryM();
        $cateLst=$cateM->cateTree();
        $this->assign('cateLst',$cateLst);
        $this->assign('cur_info',$cur_info);

       return $this->fetch();
    }

    public function del(){
        if(Request::instance()->isPost()){
            $id=input('post.id');
            $cateM=new categoryM();
            //删除子集栏目
            $sonIds=$cateM->getAllIds($id);
            $res=Db::table('category')->delete($sonIds);
            if($res) {
                return json(['code'=>'1','msg'=>'删除数据成功']);
            }else{
                return json(['code'=>'0','msg'=>'删除数据失败']);
            }
        }
    }

    //栏目排序
    public function sort(){
        if(Request::instance()->isPost()){
            $info=input('post.');
            //进行数据的修改
            $res=Db::table('category')->update($info);
            if($res){
                return ['code'=>1,'msg'=>'排序成功'];
            }else{
                return ['code'=>0,'msg'=>'排序失败,请重试'];
            }
        }
    }





}